<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="供应商编码">
              <a-input placeholder="请输入供应商编码" v-model="queryParam.supplierCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="供应商名称">
              <a-input placeholder="请输入供应商名称" v-model="queryParam.supplierName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="供应商类型">
              <j-dict-select-tag placeholder="请选择供应商类型" v-model="queryParam.supplierType" dictCode="supplier_type"/>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="信用等级">
                <j-dict-select-tag placeholder="请选择信用等级" v-model="queryParam.creditLevel" dictCode="supplier_credit_level"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="合作状态">
                <j-dict-select-tag placeholder="请选择合作状态" v-model="queryParam.cooperationStatus" dictCode="supplier_cooperation_status"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExport">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :action="importUrl"
        :headers="tokenHeader"
        @change="handleImportChange">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        
        <template slot="supplierTypeSlot" slot-scope="text">
          <j-dict-tag :value="text || ''" dictCode="supplier_type"/>
        </template>
        
        <template slot="creditLevelSlot" slot-scope="text">
          <j-dict-tag :value="text || ''" dictCode="supplier_credit_level" :colors="creditLevelColors"/>
        </template>
        
        <template slot="cooperationStatusSlot" slot-scope="text">
          <j-dict-tag :value="text || ''" dictCode="supplier_cooperation_status" :colors="cooperationStatusColors"/>
        </template>
        
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->
    
    <!-- 供应商表单模态框 -->
    <supplier-modal ref="modalForm" @ok="modalFormOk"></supplier-modal>
    
    <!-- 供应商详情模态框 -->
    <supplier-detail-modal ref="detailModal"></supplier-detail-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JDictTag from '@/components/dict/JDictTag.vue'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import { supplierList, supplierDelete, supplierBatchDelete, supplierExport } from '@/api/wms/supplier'
  import SupplierModal from './modules/SupplierModal'
  import SupplierDetailModal from './modules/SupplierDetailModal'

  export default {
    name: "SupplierList",
    mixins: [JeecgListMixin],
    components: {
      JDictSelectTag,
      JDictTag,
      SupplierModal,
      SupplierDetailModal
    },
    data() {
      return {
        description: '供应商管理页面',
        // 查询条件
        queryParam: {},
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '供应商编码',
            align: "center",
            dataIndex: 'supplierCode'
          },
          {
            title: '供应商名称',
            align: "center",
            dataIndex: 'supplierName'
          },
          {
            title: '供应商类型',
            align: "center",
            dataIndex: 'supplierType',
            scopedSlots: { customRender: 'supplierTypeSlot' }
          },
          {
            title: '联系人',
            align: "center",
            dataIndex: 'contactPerson'
          },
          {
            title: '联系电话',
            align: "center",
            dataIndex: 'contactPhone'
          },
          {
            title: '信用等级',
            align: "center",
            dataIndex: 'creditLevel',
            scopedSlots: { customRender: 'creditLevelSlot' }
          },
          {
            title: '合作状态',
            align: "center",
            dataIndex: 'cooperationStatus',
            scopedSlots: { customRender: 'cooperationStatusSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: { customRender: 'action' }
          }
        ],
        importUrl: window._CONFIG['domianURL'] + "/wms/supplier/importExcel",
        url: {
          list: "/wms/supplier/list",
          delete: "/wms/supplier/delete",
          deleteBatch: "/wms/supplier/deleteBatch",
          importExcelUrl: "wms/supplier/importExcel",
          exportXlsUrl: "wms/supplier/exportXls"
        },
        // 展开收起查询条件
        toggleSearchStatus: false,
        // 信用等级颜色
        creditLevelColors: {
          '1': '#f50', // 差 - 红色
          '2': '#fa8c16', // 一般 - 橙色
          '3': '#faad14', // 中等 - 黄色
          '4': '#52c41a', // 良好 - 绿色
          '5': '#2f54eb' // 优秀 - 蓝色
        },
        // 合作状态颜色
        cooperationStatusColors: {
          '0': '#52c41a', // 合作中 - 绿色
          '1': '#faad14', // 暂停合作 - 黄色
          '2': '#f5222d' // 终止合作 - 红色
        }
      }
    },
    methods: {
      // 展开收起查询条件
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus
      },
      // 跳转到详情页
      handleDetail(record) {
        this.$refs.detailModal.show(record);
        this.$refs.detailModal.title = "供应商详情";
      },
      // 跳转到编辑页
      handleEdit(record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑供应商";
      },
      // 跳转到新增页
      handleAdd() {
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "新增供应商";
      },
      // 删除
      handleDelete(id) {
        supplierDelete(id).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      // 批量删除
      batchDel() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择至少一条记录！')
          return
        }
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: () => {
            supplierBatchDelete(this.selectedRowKeys.join(',')).then(res => {
              if (res.success) {
                this.$message.success(res.message)
                this.loadData()
                this.onClearSelected()
              } else {
                this.$message.warning(res.message)
              }
            })
          }
        })
      },
      // 导出
      handleExport() {
        let param = {...this.queryParam}
        if(param.pageNo) delete param.pageNo
        if(param.pageSize) delete param.pageSize
        console.log('导出参数', param)
        supplierExport(param).then(data => {
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), 'supplier.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', 'supplier.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          }
        })
      },
      // 导入
      handleImportChange(info) {
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.$message.success(`${info.file.name} 文件上传成功`)
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}`)
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 文件上传失败.`)
        }
      },
      // 覆盖JeecgListMixin中的loadData方法
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        const params = this.getQueryParams();
        this.loading = true;
        supplierList(params).then((res) => {
          if (res.success) {
            // 确保数据中的null值被转换为空字符串，避免JDictTag组件报错
            const records = (res.result.records || res.result).map(item => {
              const newItem = { ...item };
              if (newItem.supplierType === null) newItem.supplierType = '';
              if (newItem.creditLevel === null) newItem.creditLevel = '';
              if (newItem.cooperationStatus === null) newItem.cooperationStatus = '';
              return newItem;
            });
            
            this.dataSource = records;
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        });
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';
</style> 